const Router = require('koa-router')
const axios = require('./utils/axios')
// const Redis = require('koa-redis')
const Website = require('../dbs/models/website')
const md5 = require('crypto-js/md5')

const mysqldb = require('../api/utils/mysql-db')
const mysqlp = require('../api/utils/mysql-p')

let router = new Router({prefix: '/website'})

router.get('/test', async (ctx) => {
  // console.log('111111111111111111', mysqldb.query)
  let email = '93977131@qq.com'
  mysqldb.query(`select * from user where email='${email}';`, [],function(result,fields){
    console.log('查询结果：');
    console.log(result);
  });
  console.log('res', res);
  ctx.body={
    code: 1,
    msg: 'test',
    res: res
  }
})

// testa
router.get('/testa', async (ctx) => {
  // mysqlp.query('select * from book', function(result,fields){
  //   console.log('查询结果：');
  //   console.log(result);
  // });
  // let res = await mysqlp.query(`select * from user;`)

  // let res = await mysqlp.query(`INSERT INTO user
  //       (email,password, username)
  //       VALUES
  //       ('93977131@qq.com','12345678','12345678');`)
  let email = '93977131@qq.com'
  let res = await mysqlp.query(`
    select * from user inner join website on user.username=website.user;
  `)
    console.log('查询结果2：');
    console.log(res);
  ctx.body={
    code: 1,
    msg: 'testa',
    res: res
  }
})

// router.get('/test', async (ctx) => {
//   ctx.body={
//     code:0,
//     msg: 'ok'
//   }
// })

// 网址收藏列表
router.get('/siteList', async (ctx) => {
  if (!ctx.isAuthenticated()) {
    ctx.body={
        code: -1
      }
    return
  }
  // let {
  //     user
  //   } = ctx.request.body
  let siteListDef = [{'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5},
                     {'name': '07ge', 'url': 'https://www.07ge.com', 'description': '07ge网址分享', 'score': 5}]
  // try {
    // console.log('user', ctx.session.passport.user.email)
    // let result = await Website.findOne({user: ctx.session.passport.user.email}).sort('-time')
    let result = await mysqlp.query(`select * from website where user='${ctx.session.passport.user.email}';`)
    if (result[0]) {
      result[0].favorite = JSON.parse(result[0].favorite)
    }
    // console.log('result2', JSON.parse(result[0].favorite))
    // result[0].favorite = JSON.parse(result[0].favorite)
    // console.log('result', result[0])
    
    if(result[0]) {
      ctx.body={
        code: 1,
        data: result[0]
      }
    } else {
      ctx.body={
        code: 0,
        data: siteListDef
      }
    }
  // } catch (error) {
  //   ctx.body={
  //     code: -1
  //   }
  // }
})

router.post('/creact', async (ctx) => {
  // console.log('222222222222222')
  if (ctx.isAuthenticated()) {
    let user = ctx.session.passport.user.email
    // let user = "93977131@qq.com"
    let time = new Date().getTime()
    // let favoriteNo = md5(Math.random() * 1000 + new Date().getTime()).toString()
    let favoriteNo = Math.random().toString()
    let {
      favorite
    } = ctx.request.body
    if(favorite.length > 20) {
      ctx.body = {
        code: -1,
        msg: '只能定义15个'
      }
      return
    }
    // console.log('body', ctx.request.body.favorite)
    let websitem = new Website({
      favorite,
      time,
      favoriteNo,
      user
    })
    // console.log('websitem', websitem)
    // console.log(Website)
    // let result = await website.save({favorite: favorite})

    // websitem.remove({'user': ctx.session.passport.user.email})

    let result = await mysqlp.query(`
      REPLACE INTO website 
          (favorite, favoriteNo, user)
        VALUES
          ('${JSON.stringify(favorite)}','${favoriteNo}','${user}');
    `)

    // let result = await websitem.updateOne({
    //   favorite:favorite,
    //   time:time,
    //   favoriteNo:favoriteNo,
    //   user:user
    // },{upsert:true})
    
    // ,{upsert:true}
    // let result = await website.updateOne()
    if (result) {
      ctx.body = {
        code: 0,
        msg: 'success',
        id: favoriteNo
      }
    } else {
      ctx.body = {
        code: -1
      }
    }
  } else {
    ctx.body = { 
      code: -1,
      msg: '未登录'
    }
  }
})


module.exports = router